//
//  Controller.m
//  Genesis
//
//  Created by Kristoffer Andersen on 31/12/08.
//  Copyright 2008 Kristoffer Andersen. All rights reserved.
//
//  This file is part of Genesis.
//  
//  Genesis is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//  
//  Genesis is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with Genesis.  If not, see <http://www.gnu.org/licenses/>.


#import "Controller.h"
#import "GConnection.h"


@implementation Controller


-(void)awakeFromNib
{	
	//set delegate on ConnectionController and mainWindow
	[connController setDelegate:self];
	[mainWindow setDelegate:self];
	mainWindowController = [mainWindow windowController];
	
	[statusMenu setDelegate:self];
	
	//Bring main window to front
	[NSApp activateIgnoringOtherApps:YES]; //Will force the app to be the front most app!
	[mainWindow orderFrontRegardless];
	[mainWindow makeKeyWindow];
	
}

////////////////////////////////////////////////////////////////
// Delegate methods for ConnectionController

- (void)activateStatusMenu
{
    NSStatusBar *bar = [NSStatusBar systemStatusBar];
	if (!theItem) {
		theItem = [bar statusItemWithLength:NSSquareStatusItemLength];
		[theItem retain];
		
		NSString *path = [NSString stringWithFormat:@"%@/genesis2-statuslogo.png",[[NSBundle mainBundle] resourcePath]];
		NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
		if (image) {
			[theItem setImage:image];
		}
		else {
			NSLog(@"No statusBar image was found at: %@",path);
			[theItem setTitle:@"Genesis"];
		}
		
		[theItem setHighlightMode:YES];
		[theItem setMenu:statusMenu];
		
		NSView *viewBuffer = [theItem view];
		NSLog(@"StatusItem %@ frame: (%f,%f)(%f,%f)",[theItem title],[viewBuffer frame].origin.y,[viewBuffer frame].origin.y,[viewBuffer frame].size.height,[viewBuffer frame].size.width);
		//statusView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 22.0, 22.0)];
		//[theItem setView:statusView];
		//[theItem setView:viewBuffer];
		
	}
}

- (void)aConnectionSucceeded
{
	//A connection was made
	
	
	//Set animations Dict for transform the window to a statusItem
	NSDictionary *animationTrans = [[NSDictionary alloc] initWithObjectsAndKeys:mainWindow,NSViewAnimationTargetKey,[NSValue valueWithRect:NSMakeRect(900.0, 900.0, 22.0, 22.0)],NSViewAnimationStartFrameKey,[NSValue valueWithRect:[mainWindow frame]],NSViewAnimationEndFrameKey,NSViewAnimationFadeInEffect,NSViewAnimationEffectKey,nil];
	
	//Animate!
	NSViewAnimation *animate = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:animationTrans]];
	[animate setDuration:0.8];
	[animate setAnimationCurve:NSAnimationEaseOut];
	[animate setAnimationBlockingMode:NSAnimationBlocking];
	[animate startAnimation];
	[animate release];
	[animationTrans release];
	//Hide main window
	[mainWindow close];
	
	//start a timer if not already started
	if (timer == nil) {
		timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkTimer:) userInfo:nil repeats:YES] retain];
	}
}

-(void)showAuthWithHost:(NSString*)host andUser:(NSString*)user
{
	[authHostField setStringValue:host];
	[authUserField setStringValue:user];
	
	NSWindowController *authCtl = [authWindow windowController];
	
	if (![authWindow isVisible]) {
		if (!authCtl) {
			NSLog(@"Init new AuthWindowController...");
			authCtl = [[NSWindowController alloc] initWithWindow:authWindow];
		}
		
		[authCtl showWindow:self];
		[authWindow orderFrontRegardless];
		[authWindow makeKeyWindow];
	}
}

////////////////////////////////////////////////////////////////
// Action Methods

-(IBAction)quitGenesis:(id)sender
{
	[connController saveAllConnectionsToDisk];
	[connController terminateAllOpenConnections];
	[NSApp terminate:self];
}
-(IBAction)showMainWindow:(id)sender
{
	if (![mainWindow isVisible]) {
		if (!mainWindowController) {
			NSLog(@"Init new windowController...");
			mainWindowController = [[NSWindowController alloc] initWithWindow:mainWindow];
		}
		
		[mainWindowController showWindow:sender];
		[mainWindow setFrame:NSMakeRect(822, 400, 557, 316) display:YES];
		[mainWindow orderFrontRegardless];
		[mainWindow makeKeyWindow];
		
		NSDictionary *animationTrans = [[NSDictionary alloc] initWithObjectsAndKeys:mainWindow,NSViewAnimationTargetKey,[NSValue valueWithRect:NSMakeRect(900.0, 900.0, 22.0, 22.0)],NSViewAnimationStartFrameKey,[NSValue valueWithRect:[mainWindow frame]],NSViewAnimationEndFrameKey,NSViewAnimationFadeInEffect,NSViewAnimationEffectKey,nil];
		NSViewAnimation *animate = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:animationTrans]];
		[animate setDuration:0.4];
		[animate setAnimationCurve:NSAnimationEaseIn];
		[animate setAnimationBlockingMode:NSAnimationBlocking];
		[animate startAnimation];
		[animate autorelease];
		[animationTrans autorelease];
	}
}

-(IBAction)authConfirmButton:(id)sender
{
	[[authWindow windowController] close];
}
-(IBAction)authCancelButton:(id)sender
{
	[[authWindow windowController] close];
}

////////////////////////////////////////////////////////////////
// Delegate for mainWindows

- (BOOL)windowShouldClose:(id)window
{
	if (window == mainWindow && !theItem) { //statusItem must not be active!
		NSLog(@"mainWindow identified!");
		[connController terminateAllOpenConnections];
		//Stop timer
		[timer invalidate];
		[timer release];
		[NSApp terminate:self];
	}
	else {
		[window close];
		//Quit if no open connections!
		if (![connController hasOpenConnections]) [self quitGenesis:window];
	}
	return NO;
}

- (void)menuWillOpen:(NSMenu *)menu
{
	if (menu == statusMenu) {
		if ([connController hasOpenConnections]) [statusMenuQuit setTitle:@"Disconnect & Quit"];
		else [statusMenuQuit setTitle:@"Quit"];
		
		if ([mainWindow isVisible]) [statusMenuShowConn setEnabled:NO];
		else [statusMenuShowConn setEnabled:YES];
	}
}

////////////////////////////////////////////////////////////////
// Timer Notification

-(void)checkTimer:(NSTimer *)aTimer
{
	//If connections still are open
	if ([connController hasOpenConnections]) {
		//count one second up
		timerSecs += 1;
		if (timerSecs >= 60) {
			timerMins += 1;
			timerSecs = 0;
		}
		if (timerMins >= 60) {
			timerHours += 1;
			timerMins = 0;
		}
	}
	//If not stop the timer!
	else {
		[timer invalidate];
		[timer release];
		timer = nil;
		
		//set new timer menu value
		timerSecs = 0;
		timerMins = 0;
		timerHours = 0;
	}
	//Update menu
	[self timerValueAsString];
}

-(void)timerValueAsString
{
	//Only display hours if positive
	NSString *hours;
	if (timerHours > 0) {
		hours = [NSString stringWithFormat:@"%i:",timerHours];
	}
	else {
		hours = @""; //empty string - don't display hours
	}
	
	//2 cipher minute display
	NSString *minutes;
	if (timerMins >9 || timerMins == 0) {
		minutes = [NSString stringWithFormat:@"%i",timerMins];
	}
	else {
		minutes = [NSString stringWithFormat:@"0%i",timerMins];
	}
	
	//2 cipher seconds display
	NSString *secs;
	if (timerSecs >9) {
		secs = [NSString stringWithFormat:@"%i",timerSecs];
	}
	else {
		secs = [NSString stringWithFormat:@"0%i",timerSecs];
	}
	
	[statusMenuTimer setTitle:[NSString stringWithFormat:@"%@%@:%@",hours,minutes,secs]];
}

////////////////////////////////////////////////////////////////
// Old Action methods from Genesis ver. 1.0

/*
-(IBAction)connectButton:(id)sender
{
	[spinner startAnimation:sender];
	[statusLabel setStringValue:@"connecting..."];
	[connectButton setEnabled:NO];
	mySSH = [[shhTunnel alloc] init];
	[mySSH initSSHTunnel:[username stringValue] host:[serverHost stringValue] portLocalForward:5480 portRemoteForward:548 forwardHost:@"localhost"];
	[mySSH connectSSH];
	
}

-(IBAction)disconnectButton:(id)sender
{
	[statusLabel setStringValue:@"disconnecting..."];
	[myBonjour stopService];
	[myBonjour release];
	[disconnectButton setEnabled:NO];
	[mySSH terminateSSH];
	//[mySSH release];
	//mySSH = nil;
	[connectButton setEnabled:YES];
	[statusLabel setStringValue:@"ready"];
}

-(IBAction)toggleConsole:(id)sender
{
	//[consoleDrawer toggle:sender];
}
*/

////////////////////////////////////////////////////////////////
// Notifications from Genesis ver. 1.0
/*
-(void)ConnectionSuccesNotification:(NSNotification *)aNotification
{
	[disconnectButton setEnabled:YES];
	[statusLabel setStringValue:@"connected"];
	
	//Init bonjour
	myBonjour = [[tunBonjour alloc] init];
	[myBonjour createService:[serverHost stringValue] type:@"_afpovertcp._tcp." port:5480 host:@"localhost"];
	[spinner stopAnimation:self];
}

-(void)ConnectionInteruptedNotification:(NSNotification *)aNotification
{
	//[console insertText:@"Connection interruptet!\n"];
	NSBeep();
	[statusLabel setStringValue:@"Error!"];
	[mySSH terminateSSH];
	[connectButton setEnabled:YES];
	[disconnectButton setEnabled:NO];
	[spinner stopAnimation:self];
	
	//If loaded, stop bonjour
	if (myBonjour) {
		[myBonjour stopService];
		[myBonjour release];
	}
}

-(void)ConnectionDidPostTextNotification:(NSNotification *)aNotification
{
	//[console insertText:[aNotification object]];
}
*/




@end
